package com.sskj.gocoin.v.fragment;

import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.ClassicsHeader;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.common.rxbus2.RxBus;
import com.sskj.gocoin.common.rxbus2.Subscribe;
import com.sskj.gocoin.common.rxbus2.ThreadMode;
import com.sskj.gocoin.common.widget.ToolBarLayout;
import com.sskj.gocoin.m.bean.AppVersionBean;
import com.sskj.gocoin.m.bean.Menu;
import com.sskj.gocoin.m.bean.UserInfo;
import com.sskj.gocoin.p.activity.MinePresenter;
import com.sskj.gocoin.utils.APKVersionCodeUtils;
import com.sskj.gocoin.utils.SPUtils;
import com.sskj.gocoin.utils.StringUtils;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.AboutUsActivity;
import com.sskj.gocoin.v.activity.ApplyAgentPersonActivity;
import com.sskj.gocoin.v.activity.AssetManageActivity;
import com.sskj.gocoin.v.activity.CashAddressListActivity;
import com.sskj.gocoin.v.activity.ExchangeActivity;
import com.sskj.gocoin.v.activity.GoogleSettingActivity;
import com.sskj.gocoin.v.activity.InforMationActivity;
import com.sskj.gocoin.v.activity.LoginActivity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.PersonalActivity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.gocoin.v.activity.ShareActivity;
import com.sskj.gocoin.v.activity.ShareDetailActivity;
import com.sskj.gocoin.v.activity.WKActivity;
import com.sskj.gocoin.v.base.BaseFragment;

import java.util.ArrayList;

import butterknife.BindView;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;


/**
 * Created by Lee on 2018/2/28 0028.
 */

public class MineFragment extends BaseFragment<MainActivity, MinePresenter> {

    @BindView(R.id.mine_user_balance)
    TextView mMineUserBalance;
    @BindView(R.id.mine_property_type)
    TextView mMinePropertyType;
    @BindView(R.id.toolBar)
    ToolBarLayout mToolBar;
    @BindView(R.id.menu)
    RecyclerView menuRecyclerView;

    @BindView(R.id.refresh)
    SmartRefreshLayout refreshLayout;

    private BaseAdapter<Menu> adapter;
    private ArrayList<Menu> menus;


    private MaterialDialog tip;
    private int applyStatus;
    private AlertDialog tipDialog;
    private AlertDialog tipErrorDialog;
    private Object applyRefuseReason;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

//    @Subscribe(code = Constants.USER_LOGIN, threadMode = ThreadMode.MAIN)
//    public void userLogin() {
////        mActivity.mMobile = (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_MOBILE, "");
////        Constants.mIsLogin = (boolean) SPUtils.get(MyAppLication.getApplication(), Constants.SP_LOGIN_STATUS, false);
//        mPresenter.requestUserInfo(MyAppLication.getMobile());
//    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (MyAppLication.isLogin()) {
                if (!TextUtils.isEmpty(MyAppLication.getMobile())) {
                    mPresenter.requestUserInfo(MyAppLication.getMobile());
                }
            }
        }
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initPreView();
        RxBus.getDefault().register(this);
//        mActivity.mMobile = (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_MOBILE, "");
        if (TextUtils.isEmpty(MyAppLication.getMobile()) || !MyAppLication.isLogin()) {
            logout();
        } else {
            if (mActivity.mUserInfo != null) {
                loginSuccess(mActivity.mUserInfo);
            }
        }

    }


    @Override
    public void initView() {

        mToolBar.setRightButtonIcon(getResources().getDrawable(R.mipmap.icon_sign));
        //签到
        mToolBar.setRightButtonOnClickLinster(v -> {
            if (MyAppLication.isLogin()) {
                mPresenter.sign();
            } else {
                startActivity(new Intent(mActivity, LoginActivity.class));
            }
        });
        mToolBar.mLeftButton.setTextColor(ContextCompat.getColor(getContext(), R.color.text_color));

        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        refreshLayout.setOnRefreshListener(v -> mPresenter.requestUserInfo(MyAppLication.getMobile()));

        menuRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        menus = new ArrayList<>();
        adapter = new BaseAdapter<Menu>(R.layout.item_main_menu, menus, menuRecyclerView) {
            @Override
            public void bind(ViewHolder holder, Menu item) {
                holder.setText(R.id.menu_title, item.getText());
                holder.setImageResource(R.id.menu_icon, item.getIcon());
                if ((holder.getAdapterPosition() + 1) % 3 == 0 && holder.getAdapterPosition() != 0) {
                    holder.setVisible(R.id.menu_right_line, false);
                } else {
                    holder.setVisible(R.id.menu_right_line, true);
                }
                if (menus.size() % 3 == 0) {
                    if (holder.getAdapterPosition() + 1 > 3 * (menus.size() / 3 - 1)) {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    } else {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    }
                } else {
                    if ((holder.getAdapterPosition() + 1) > (menus.size() - menus.size() % 3)) {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    } else {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    }
                }
            }
        };
        adapter.setOnItemClickListener((adapter, view, position) -> {
            switch (position) {
                case 0:
                    //个人中心
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, PersonalActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }
                    break;
                case 1:
                    //安全中心
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, SecurityCenterActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }
                    break;
                case 2:
                    //资产管理
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, AssetManageActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }
                    break;
                case 3:
                    //提币地址管理
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, CashAddressListActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }
                    break;
                case 4:
                    //duihuan
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, ExchangeActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }

                    break;
                case 5:
                    //平台公告
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, InforMationActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }
                    break;
                case 6:
                    //我的推广
                    if (MyAppLication.isLogin()) {
                        startActivity(new Intent(mActivity, ShareActivity.class));
                    } else {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    }
                    break;
                case 7:
                    //推广明细
                    ShareDetailActivity.start(getContext());
                    break;
                case 8:
                    //挖矿
                    WKActivity.start(getContext());
                    break;
                case 9:
                    startActivity(new Intent(mActivity, AboutUsActivity.class));
                    break;
                case 10:
                    // 设置
                    GoogleSettingActivity.start(mActivity, 0);
                    break;
                case 11:
                    //版本更新
                    mPresenter.getVersion();
                    break;

            }
        });
        menuRecyclerView.setAdapter(adapter);

    }

    private void initPreView() {
        String verName = APKVersionCodeUtils.getVerName(mActivity);
    }

    /**
     * 显示经纪人申请跳转提示
     */
    private void showApplyTip() {
        if (tipDialog == null) {
            tipDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(App.INSTANCE.getString(R.string.strMineFragment214))
                    .setMessage(App.INSTANCE.getString(R.string.strMineFragment215))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strMineFragment216), (dialog, which) -> {
                        dialog.dismiss();
                        ApplyAgentPersonActivity.start(getActivity());
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strMineFragment217), (dialog, which) -> dialog.dismiss()).create();
        }
        tipDialog.show();
    }


    /**
     * 显示经纪人重新申请跳转提示
     */
    private void showReApplyTip() {
        tipErrorDialog = new AlertDialog.Builder(getActivity())
                .setTitle(App.INSTANCE.getString(R.string.strMineFragment218))
                .setMessage(App.INSTANCE.getString(R.string.strMineFragment219) + applyRefuseReason)
                .setPositiveButton(App.INSTANCE.getString(R.string.strMineFragment220), (dialog, which) -> {
                    dialog.dismiss();
                    ApplyAgentPersonActivity.start(getActivity());
                })
                .setNegativeButton(App.INSTANCE.getString(R.string.strMineFragment217), (dialog, which) -> dialog.dismiss()).create();
        tipErrorDialog.show();
    }

    public void updateUserTitle(UserInfo user) {
        SPUtils.putBean(mActivity, Constants.SP_USER_INFO, user);
        loginSuccess(user);

    }

    private void loginSuccess(UserInfo user) {
        applyStatus = user.getIs_apply();
        applyRefuseReason = user.getApply_reason();
//        mMinePropertyType.setVisibility(View.VISIBLE);
//        mMineUserBalance.setVisibility(View.VISIBLE);
        if (user.getQd() == 0) {
            mToolBar.setRightButtonText("");
            mToolBar.mRightButton.setEnabled(true);
            mToolBar.setRightButtonIcon(ContextCompat.getDrawable(getContext(), R.mipmap.icon_sign));
        } else {
            mToolBar.setRightButtonText(getString(R.string.signed));
            mToolBar.mRightButton.setTextColor(getResources().getColor(R.color.text_color));
            mToolBar.mRightButton.setEnabled(false);
            mToolBar.mRightButton.setCompoundDrawables(null, null, null, null);
        }

        String mobile = MyAppLication.getMobile();
        mToolBar.setLeftButtonText(StringUtils.changeText(mobile));
        mToolBar.setLeftButtonIcon(getResources().getDrawable(R.mipmap.icon_avatar));
        mToolBar.setLeftButtonEnable(false);
        mMineUserBalance.setText(user.wallone);
    }

    @Subscribe(code = Constants.USER_LOGOUT, threadMode = ThreadMode.MAIN)
    public void logout() {
        SPUtils.clear(MyAppLication.getMobile());
        //重新初始化公共头
        MyAppLication.getApplication().initOkgoHttp();
        mToolBar.setLeftButtonIcon(getResources().getDrawable(R.mipmap.icon_avatar));
        mToolBar.setLeftButtonText(App.INSTANCE.getString(R.string.strMineFragment224));
//        tvUid.setText(getResources().getText(R.string.welcome));
        mToolBar.setLeftButtonEnable(true);
        mActivity.mUserInfo = null;
        mToolBar.hideRightImgView();
//        tvUid.setTextSize(TypedValue.COMPLEX_UNIT_PT, 24);
//        tvUid.setTextColor(getResources().getColor(R.color.colorHintLine));
        mToolBar.setLeftButtonOnClickLinster(v -> startActivity(new Intent(getActivity(), LoginActivity.class)));
        mMineUserBalance.setText("---");
//        mMinePropertyType.setText(App.INSTANCE.getString(R.string.strMineFragment223));
    }


    @Override
    public void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (MyAppLication.isLogin()) {
            if (!TextUtils.isEmpty(MyAppLication.getMobile())) {
                mPresenter.requestUserInfo(MyAppLication.getMobile());
            }
        }
    }


    /**
     * 签到成功
     *
     * @param data
     */
    public void signSuccess(String data) {
        mToolBar.setRightButtonText(getString(R.string.signed));
        mToolBar.mRightButton.setEnabled(false);
        mToolBar.mRightButton.setTextColor(getResources().getColor(R.color.text_color));
        mToolBar.setRightButtonIcon(null);
    }

    public void stopRefresh() {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }
        String verName = APKVersionCodeUtils.getVerName(mActivity);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(versionBean.getVersion(), verName) == 1) {
            FragmentTransaction fragmentTransaction = mActivity.getFragmentManager().beginTransaction();
            getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            appUpDateFragment.show(fragmentTransaction, "update");
        } else {
            ToastUtil.showShort("当前已是最新版本");
        }
    }
}
